<template>
  <el-dialog
    :visible.sync="visible"
    title="修改密码"
    @close="handleClose"
    append-to-body
    width="500px"
  >
      <el-form
        :model="passwordForm"
        :rules="passwordRules"
        ref="passwordFormRef"
        label-width="120px"
      >
        <el-form-item label="原密码" prop="oldPassword">
          <el-input
            type="password"
            v-model="passwordForm.oldPassword"
            auto-complete="off"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input
            type="password"
            v-model="passwordForm.password"
            auto-complete="off"
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            type="password"
            v-model="passwordForm.confirmPassword"
            auto-complete="off"
          />
        </el-form-item>
      </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  name: 'PasswordModal',
  data() {
    return {
      visible:false,
      passwordForm: {
        oldPassword: '',
        password: '',
        confirmPassword: '',

      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.password) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ]
      }
    };
  },
  methods: {
    open() {
      this.visible = true;
      this.$refs.passwordFormRef.resetFields();
    },
    handleClose() {
        this.visible = false;
    },
    handleCancel() {
      this.$refs.passwordFormRef.resetFields();
      this.visible = false;
    },
    handleSubmit() {
      this.$refs.passwordFormRef.validate(valid => {
        if (valid) {
          this.$httpApi.updatePassword(this.passwordForm).then((res) => {
            if (res.success) {
                this.$message.success('操作成功');
                this.visible=false
            }
            else{
              this.$message.error(res.msg);
            }
          })
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    }
  }
};
</script>
